import { Icon, Tooltip, Input, SelectNew, Button, Popover, message, Popconfirm } from 'antd';
import { inject, observer } from 'mobx-react';
import React from 'react';
import classNames from 'classnames';
import { WeaLocaleProvider, WeaFormItem, WeaInput, WeaTag, WeaError } from 'ecCom';
import TabStore from "../../stores/modetab/TabStore"
const getLabel = WeaLocaleProvider.getLabel;
const Option = SelectNew.Option;
import jQuery from "jquery";
import TagSet from './tagSet';
import { tagsJson } from './tagdata';

export interface modeTabProps {
    TabStore: TabStore;
}

@inject("TabStore")
@observer
export default class ModeTab extends React.Component<any, any>  {
    timer;
    isSelect = false;
    isEdit = false;
    constructor(props) {
        super(props);
        this.state = {
            value: '',
            focus: false,
            color: '#eb2f96',
            bgcolor: '#fff0f6',
            bdcolor: '#ffadd2',
            tabname: '',
            visible: false,
            id: '',
            addTabVisible: false,
            tags: []
        }
    }

    componentDidMount() {
        let { modeid, billid, TabStore, container } = this.props;
        TabStore.initData(modeid, billid);
        jQuery(container).on('click', this.click);
    }


    click = () => {
        const that = this;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            that.setState({ visible: false, addTabVisible: false, value: '', tabname: '' })
        }, 300);
    }

    render() {
        return this.renderModal();
    }

    handleFocus = (e) => {
        jQuery(this.props.container).off('click', this.click);
        this.setState({ visible: false, tabname: '' });
        jQuery(".tabsDiv .ant-select-search__field").click()//点击添加标签要自动显示下拉框
        return false;
    }

    handleFocusBlur = (e) => {
        jQuery(this.props.container).on('click', this.click);
        this.setState({
            focus: e.target === document.activeElement,
        });
    }

    renderModal = () => {
        const { TabStore } = this.props;
        const { existTabs } = TabStore;
        const btnCls = classNames({
            'ant-search-btn': true,
            'ant-search-btn-noempty': !!this.state.value.trim(),
        });
        const searchCls = classNames({
            'ant-search-input': true,
            'ant-search-input-focus': this.state.focus,
        });

        const { tabs } = TabStore;
        let options = tabs && tabs.map(tab =>
            <Option key={tab.id}>
                <div style={{display:'none'}}>{JSON.stringify(tab)}</div>
                <div title={tab.tabname}  className="cube-mode-tag wev-cube-menu-item-text" style={{
                    color: tab.color,
                    background: tab.bgcolor,
                    borderColor: tab.bdcolor,
                    width:100
                }}>{tab.tabname}</div>
                {tab.selected &&
                    <Icon type="check" style={{ color: '#1890ff', float: 'right' }} />
                }
                {
                    this.props.billid == '' && this.checkTabExist(tab.id) &&
                    <Icon type="check" style={{ color: '#1890ff', float: 'right' }} />
                }
                {tab.edit && <div title={getLabel(93, "编辑")} id={"groupBtnEdit_" + tab.id} className="wev-cube-menu-item-icon">
                    <span className="icon-coms-edit" onClick={() => this.editClick(tab.tabname, tab.color, tab.bgcolor, tab.bdcolor, tab.id)}></span>
                    {/* <Icon type="edit"  /> */}
                </div>}
            </Option>
        );
        return (<div className="tabsDiv">
            {existTabs && existTabs.map((tagObj, index) => {//卡片页面使用
                let tag = tagObj.tabname;
                let id = tagObj.id
                let color = tagObj.color;
                const isLongTag = tag.length > 20;
                const tagElem = (
                    <WeaTag  style={{color:color,backgroundColor:tagObj.bgcolor,borderColor:tagObj.bdcolor}} color={color} key={id} closable={tagObj.canDelete} afterClose={() => this.handleClose(tagObj)}>
                        {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                    </WeaTag>
                );
                return isLongTag ? <Tooltip title={tag} key={id}>{tagElem}</Tooltip> : tagElem;
            })}
            {this.state.tags && this.state.tags.map((tagObj, index) => {//查询列表页面使用
                let tag = tagObj.tabname;
                let id = tagObj.id
                let color = tagObj.color;
                const isLongTag = tag.length > 20;
                const tagElem = (
                    <WeaTag style={{'border-radius': '4px',color:color,backgroundColor:tagObj.bgcolor,borderColor:tagObj.bdcolor}} color={color} key={id} closable={true} afterClose={() => this.handleClose(tagObj)}>
                        {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                    </WeaTag>
                );
                return isLongTag ? <Tooltip title={tag} key={id}>{tagElem}</Tooltip> : tagElem;
            })}
            {this.state.addTabVisible && <div className="wev-cube-tab-dropdown">
                <div className="ant-search-input-wrapper" style={{ width: 235 }}>
                    <Input.Group className={searchCls}>
                        <SelectNew
                            combobox
                            value={this.state.value}
                            notFoundContent=""
                            defaultActiveFirstOption={false}
                            showArrow={false}
                            filterOption={this.selectFilterOption}
                            onChange={this.handleChange}
                            onBlur={this.handleFocusBlur}
                            onSelect={this.selectClick}
                            onFocus={this.handleFocus}
                            autoFocus={true}
                        >
                            {options}
                        </SelectNew>
                        <div className="ant-input-group-wrap">
                            <Popover placement="bottomRight" visible={this.state.visible} title={this.getTitle()} content={this.getContent()} trigger="click">
                                <Button className={btnCls} onClick={this.add} >
                                    <Icon type="plus-circle-o" />
                                </Button>
                            </Popover>
                        </div>
                    </Input.Group>
                </div>
            </div>}
            {!this.state.addTabVisible && (
                <WeaTag
                    className={`otherTag `}
                    onClick={this.showInput}>
                    <Icon type="plus" />{getLabel(81324, "添加标签")}
                </WeaTag>)}
        </div>);
    }

    checkTabExist = (value) => {//批量设置时判断标签是否被选择
        let result = false;
        this.state.tags.map((tab) => {
            if (tab.id == value) {
                result = true;
            }
        });
        return result;
    }

    getTitle = () => {
        if (this.state.id == '') {
            return getLabel(83263, "新建标签")
        } else {
            return getLabel(83264, "编辑标签")
        }
    }

    editClick = (tabname, color, bgcolor, bdcolor, id) => {
        this.setState({ visible: !this.state.visible, tabname: tabname, color: color, bgcolor, bdcolor, id: id });
        this.isEdit = true;
    }

    inputChange = (v) => this.setState({ tabname: v })

    tagSetChange = (obj) => { this.setState(obj) }
    getContent = () => {
        return (
            <div style={{ width: 200 }} className="wev-cube-tab-form">
                <WeaFormItem
                    label={getLabel(81323, '标签名称')}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                >
                    <WeaError tipPosition='bottom' error={getLabel(81323, '标签名称') + getLabel(21423, "未填写")}
                        style={{ width: "100%" }}
                        ref="tagAdd"
                    >
                        <WeaInput value={this.state.tabname} onChange={this.inputChange} viewAttr={3} />
                    </WeaError>
                </WeaFormItem>
                <br />
                <WeaFormItem
                    label={getLabel(500433, "样式模板")}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                >
                    {this.getTagsSelectDemo()}
                </WeaFormItem>
                <br />
                <TagSet
                    color={this.state.color}
                    bgcolor={this.state.bgcolor}
                    bdcolor={this.state.bdcolor}
                    onChange={this.tagSetChange}
                />
                <WeaFormItem
                    label={''}
                    labelCol={{ span: 0 }}
                    wrapperCol={{ span: 24 }}
                >
                    {this.state.id == '' ?//创建
                        <Button className="wev-cube-tab-addButton" type="primary" size="large" onClick={this.saveTab}>{getLabel(125, "创建")}</Button>
                        ://编辑
                        <div>
                            <Popconfirm title={getLabel('385240', "确认删除标签？")} okText={getLabel(826, "确定")} cancelText={getLabel(201, "取消")} onConfirm={this.delTab}>
                                <Button className="wev-cube-tab-delButton" type="primary" size="large" >{getLabel(23777, "删除")}</Button>
                            </Popconfirm>
                            <Button onClick={this.saveTab} className="wev-cube-tab-okButton" type="primary" size="large" >{getLabel(555, "完成")}</Button>
                        </div>
                    }
                </WeaFormItem>
            </div>
        );
    }

    delTab = () => {
        const { billid, TabStore, modeid } = this.props;
        let parm = { id: this.state.id, billid: billid, modeid: modeid, tablename: TabStore.tablename }
        TabStore.delSingtonTab(parm);
        clearTimeout(this.timer);
        const tags = [...this.state.tags];
        tags.splice(tags.findIndex(item => item.id === this.state.id), 1);
        this.setState({ visible: !this.state.visible, tabname: '', tags: tags });
    }
    saveTab = () => {
        if (this.state.tabname == '') {
            this.refs.tagAdd["showError"]();
            // message.error(getLabel(384148, "必填项不能为空!"));
            return;
        }
        if (this.state.tabname.length > 16) {
            message.error(getLabel(385735, "标签名太长!"));
            return;
        }
        const { billid, TabStore, modeid } = this.props;
        let parm = { id: this.state.id, tabname: this.state.tabname, color: this.state.color,bgcolor:this.state.bgcolor,bdcolor:this.state.bdcolor, billid: billid, modeid: modeid }
        TabStore.saveSingtonTab(parm, this.addTabForListShow);
        clearTimeout(this.timer);
        this.setState({ visible: !this.state.visible, addTabVisible: false, value: '', tabname: '' });
    }
    add = (e) => {
        clearTimeout(this.timer);
        this.setState({ visible: !this.state.visible, color: '#000', id: '' });
        if (this.state.value == '') {
            this.setState({ tabname: '' });
        }
    }

    //查询列表新建标签也要选中
    addTabForListShow = (parm) => {
        if (parm.billid == '') {//如果是查询列表
            const tags = [...this.state.tags];
            tags.push({ id: parm.id, tabname: parm.tabname, color: parm.color,bgcolor:parm.bgcolor,bdcolor:parm.bdcolor });
            this.setState({ tags: tags, visible: false });
        }
    }


    /**
     * 根据选择框的名称，搜索过滤选项
     * @param value 
     * @param option 
     */
    selectFilterOption = (value, option) => {
        if (value != "") {
            const { children } = option["props"];
            if (children) {
                let namediv = children[1]["props"].children;
                return namediv.toLowerCase().indexOf(value.toLowerCase()) != -1;
            } else {
                return false;
            }
        }
        return true;
    }

    handleChange = (value) => {
        if (!this.isSelect) {
            this.setState({ value: value, tabname: value });
        }
        this.isSelect = false;
    }

    selectClick = (value, option) => {
        const { billid, TabStore, modeid } = this.props;
        let isadd = true;
        let modelableid = '';
        let tabid = value;
        if (billid != '') {
            TabStore.existTabs.map((tab) => {
                modelableid += tab.id + ',';
                if (tab.id == tabid) {
                    isadd = false
                }
            });
        } else {
            this.state.tags.map((tab) => {
                if (tab.id == tabid) {
                    isadd = false
                }
            });
        }
        if (!this.isEdit && isadd) {
            if (billid != '') {
                modelableid += tabid;
                let parm = { operate: '0', modelableid: modelableid, billid: billid, tablename: TabStore.tablename, modeid: modeid, tabid: tabid };
                TabStore.updateDataTab(parm);
                this.setState({ addTabVisible: false });
            } else {
                const { value, children } = option.props;
                let tag = JSON.parse(children[0].props.children);
                const tags = [...this.state.tags];
                tags.push({ id: value, tabname: tag.tabname, color:tag. color,bgcolor:tag.bgcolor,bdcolor:tag.bdcolor });
                this.setState({ tags: tags, visible: false });
            }
        }
        this.setState({ value: '' });
        this.isSelect = true;
        this.isEdit = false;
    }

    handleClose = (removedTag) => {
        const { billid, TabStore, modeid } = this.props;
        if (billid != '') {//卡片页面
            const tags = TabStore.existTabs.filter(tag => tag.tabname !== removedTag.tabname);
            let modelableid = '';
            TabStore.existTabs = tags;
            tags.map((tag) => {
                modelableid += tag.id + ',';
            });
            modelableid = modelableid.replace(/,$/, '');
            let parm = { operate: "1", modelableid: modelableid, billid: billid, tablename: TabStore.tablename, modeid: modeid, tabid: removedTag.id };
            TabStore.updateDataTab(parm);
        } else {//查询列表
            const tags = [...this.state.tags].filter(tag => (tag.id !== removedTag.id) && tag);
            this.setState({ tags: tags });
        }
    }


    showInput = () => {
        clearTimeout(this.timer)
        this.setState({ addTabVisible: true, value: '' });
    }
    getTagsSelectDemo = () => {
        const tags: any = [];
        tagsJson.map(item => {
            tags.push(<Option key={item.key} value={item.key}>
                <span style={{ marginRight: 5 }}>{"#" + item.key}</span>
                <div className="cube-mode-tag" style={{
                    color: item.color,
                    background: item.bgcolor,
                    borderColor: item.bdcolor
                }}
            >{getLabel(176, '标签') + item.key}</div></Option>)
        })
        return <SelectNew style={{ width: 132 }}  onChange={this.selectNewChange}  >
            {tags}
        </SelectNew>
    }

    selectNewChange = (v) => { this.setState(tagsJson[v - 1]) }

}
